<template>
  <textarea ref="mycode" class="codesql" v-model="code"></textarea>
</template>

<script>

  import "codemirror/lib/codemirror.css";
  import "codemirror/addon/hint/show-hint.css";

  require("codemirror/theme/ambiance.css");
  require ("codemirror/theme/idea.css");
  require ("codemirror/theme/monokai.css");

  require('codemirror/keymap/sublime')

  let CodeMirror = require("codemirror/lib/codemirror");
  require("codemirror/addon/edit/matchbrackets");
  require("codemirror/addon/selection/active-line");
  require("codemirror/addon/hint/show-hint");
  require("codemirror/mode/javascript/javascript");
  require("codemirror/addon/hint/javascript-hint");
    export default {
      name: "codeMirror",
      data () {
        return {
          editor:null,
          code: ''
        }
      },
      mounted () {
        // debugger
        let mime = 'javascript'
        let theme = 'idea'//设置主题，不设置的会使用默认主题
        this.editor = CodeMirror.fromTextArea(this.$refs.mycode, {
          mode: mime,//选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
          indentWithTabs: true,
          smartIndent: true,
          lineNumbers: true,
          // lineWrapping: true, // 自动换行
          matchBrackets: true, // 括号匹配显示
          autoCloseBrackets: true, // 输入和退格时成对
          // autoRefresh: true, // 自动刷新
          styleActiveLine: true, //设置光标所在行高亮，需要引入addon/selection/active-line.js
          theme: theme,
          autofocus: true,
          keyMap:'sublime',
          extraKeys: {'Ctrl': 'autocomplete'},//自定义快捷键
          hintOptions: {//自定义提示选项
              completeSingle: false,
              hint:CodeMirror.hint.javascript
              // hint: this.handleShowHint
          }
        })
        var _this = this
        this.editor.on('inputRead', function () {
          _this.editor.showHint()
        })
      },
      methods:{
        handleShowHint(cmInstance, hintOptions) {
            let cursor = cmInstance.getCursor();
            let cursorLine = cmInstance.getLine(cursor.line);
            let end = cursor.ch;
            let start = end;

            let token = cmInstance.getTokenAt(cursor)
            return {
                list: ["var","function","this"],
                from: {ch: token.start, line: cursor.line},
                to: {ch: token.end, line: cursor.line}
            };
        },
        setValue(code){
          this.editor.setValue(code)
        },
        getValue(){
          return this.editor.getValue()
        }
      }
    }
</script>

<style>
  .codesql {
    width: 80%;
    font-size: 11pt;
    font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
  }
  .CodeMirror {
    height: 100%;
  }
  .cm-s-idea{
    height: 100%;
  }
</style>